import { h }    from 'snabbdom/build/package/h'
import { init } from 'snabbdom/build/package/init'
// 下面内容请按需导入
import { classModule } from 'snabbdom/build/package/modules/class'
import { propsModule } from 'snabbdom/build/package/modules/props.js'
import { styleModule } from 'snabbdom/build/package/modules/style.js'
import { eventListenersModule } from 'snabbdom/build/package/modules/eventlisteners.js'

const patch = init([
    classModule,
    propsModule,
    styleModule,
    eventListenersModule
])

let data = [
    {id: 1, name: '西瓜', content: '我喜欢吃西瓜'},
    {id: 2, name: '苹果', content: '我喜欢吃苹果'},
    {id: 3, name: '桃子', content: '我喜欢吃桃子'},
]

const vContent = function () {
    let dom = []
    data.forEach((item, index) => {
        dom.push(h('div', [
            h('span', item.id),
            h('span', { style: {display: 'inline-block', margin: '10px', fontWeight: 'bold' } }, item.name),
            h('span', item.content),
            h('span', { style: {display: 'inline-block', color: 'red', marginLeft: '10px' }, on: { click: () => headleClick(item.id) } }, 'x')
        ]))
    })
    return dom
}

const vHeader = function () {
    return h('div', [
        h('span', {on: { click: () => headerAdd() }}, 'Add')
    ])
}

const composeNode = function () {
    return h('div', [
       vHeader(),
       h('div', vContent())
    ])
}

let vnode = h('div', composeNode())

let app = document.getElementById('content');

let oldNode = patch(app, vnode)

const headleClick = function (id) {
    
    data = data.filter(item => item.id !== id)
    vnode = h('div', composeNode())
    oldNode = patch(oldNode,  vnode)
}

const headerAdd = function() {
    // 获取最大index
    let maxId = data.map(item => item.id)
    maxId.sort((a,b) => b - a)
    data.push({id: maxId[0] + 1, name: '其他', content: '我喜欢其他'},)
    vnode = h('div', composeNode())
    oldNode = patch(oldNode,  vnode)
}